<?php
namespace core;

use core\tpl\TwigTpl;
use core\tpl\PhpTpl;
use core\tpl\Tpl;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;


class Controller {
    public function __construct($method) {
        $method = $method ?: DEFAULT_METHOD; //如果没有方法则使用默认方法
        define('METHOD', $method);
        $this->{$method}(); //执行控制器类方法
    }

    public function __call($method, $arg) {
        if (DEFAULT_METHOD == $method) {
            header('HTTP/1.1 404 Not Found');
            trigger_error("ERROR! Can't find {$method} in " . get_class($this), E_USER_ERROR);
        } else {
            define('METHOD', DEFAULT_METHOD);
            $this->{DEFAULT_METHOD}();
        }
    }


    public function assign($key, $val) {
        $this->_template();
        $this->_tpl->assign($key, $val);
    }
    public function import($filename = '') {
        $this->_template();
        $this->_tpl->import($filename);
    }
    /** @var Tpl  */
    private $_tpl = null;
    private function _template() {
        if ($this->_tpl) return;

        if (APP_TPL == 'php') {
            $this->_tpl = new PhpTpl(PATH_VIEW);
        } else if (APP_TPL == 'twig') {
            // 检查缓存目录是否定义
            defined('PATH_TWIG_CACHE') or define('PATH_TWIG_CACHE', PATH_RUNTIME . 'twig/');
            // 确认缓存目录存在
            path_sure(PATH_TWIG_CACHE);

            $this->_tpl = new TwigTpl(PATH_VIEW, PATH_TWIG_CACHE);
        } else {
            exit('没有定义 ' . APP_TPL . ' 模板引擎');
        }
    }


    public function debug($message, array $content = []) {
        $this->logCreate();
        $this->_log->debug($message, $content);
    }
    public function info($message, array $content = []) {
        $this->logCreate();
        $this->_log->info($message, $content);
    }
    public function error($message, array $content = []) {
        $this->logCreate();
        $this->_log->error($message, $content);
    }

    /** @var Logger  */
    private $_log = null;
    public function logCreate($filename = '') {
        if ($this->_log && !$filename) return;

        $filename = $filename ?: date('Ymd') . '.log';
        $filename = PATH_LOG . $filename;

        $this->_log = new Logger('logger');
        // 用户自定义日志级别
        if (defined('APP_LOG_LEVEL')) {
            $this->_log->pushHandler(new StreamHandler($filename, $this->_logGetLevel(constant('APP_LOG_LEVEL'))));
        } else {
            $logLevel = APP_DEBUG ? 'debug' : 'error';
            $this->_log->pushHandler(new StreamHandler($filename, $this->_logGetLevel($logLevel)));
        }
    }
    private function _logGetLevel($levelName) {
        if ($levelName == 'debug') {
            return Logger::DEBUG;
        } else if ($levelName == 'info') {
            return Logger::INFO;
        } else {
            return Logger::ERROR;
        }
    }
}
